// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

import { _decorator, Component, Label, log, Node, ScrollView, UIOpacity, UITransform, EventHandler } from 'cc';
import NetworkManager, { SeverUrl } from '../managers/NetworkManager';
import { CommonUtils } from './CommonUtils';
import { GlobalRoot } from '../global/GlobalRoot';

const { ccclass, property } = _decorator;

@ccclass
export default class LoadScrollView extends Component {

    allNode: any = null
    currentPage = 1;
    isLoading = false;
    hasMore = true;
    serVerUrl: SeverUrl = null;
    otherInfo: any = {};
    pageSize = 10
    createItemFunc: Function = null;
    content: Node = null;
    // LIFE-CYCLE CALLBACKS:

    onLoad() {
        this.content = this.node.getChildByName("view").getChildByName("content");
    }

    start() {
        this.allNode = CommonUtils.getAllChildrenMap(this.node);
        this.node.on('scroll-ended', this.onScrollEnded, this);
        // 正确注册 scrollEvent
        const scrollView = this.node.getComponent(ScrollView);
        if (scrollView) {
            const handler = new EventHandler();
            handler.target = this.node;
            handler.component = 'LoadScrollView';
            handler.handler = 'scrollEvent';
            scrollView.scrollEvents.push(handler);
        }
    }


    /**加载本地数据 */
    initLocalUi(data: any = [], createItemFunc: Function) {
        this.createItemFunc = createItemFunc;
        this.content.removeAllChildren();

        for (let i = 0; i < data.length; i++) {
            if (this.createItemFunc)
                this.createItemFunc(this.content, data[i])
        }
        this.isLoading = true
    }



    /**加载服务器数据 */
    initServerUi(serVerUrl: SeverUrl, otherInfo: any, createItemFunc: Function) {
        this.serVerUrl = serVerUrl;
        this.otherInfo = otherInfo;
        this.createItemFunc = createItemFunc;
        this.resetPageState();
        console.log("初始化游戏页面=====================");
        this.initGamePage();
    }

    private onScrollEnded(): void {
        if (this.isLoading || !this.hasMore) return;

        const scrollView = this.node.getComponent(ScrollView);
        // 当滚动到底部时加载更多
        if (scrollView.horizontal) {
            //横向
            const offsetx = scrollView.getScrollOffset().x;
            const maxOffsetx = scrollView.getMaxScrollOffset().x;
            if (offsetx >= maxOffsetx + 50) {
                this.loadMoreData();
            }
        } else {
            //竖向
            const offsetY = scrollView.getScrollOffset().y;
            const maxOffsetY = scrollView.getMaxScrollOffset().y;

            if (offsetY <= maxOffsetY + 50) {
                this.loadMoreData();
            }
        }
    }

    private resetPageState(): void {
        this.currentPage = 1;
        this.isLoading = false;
        this.hasMore = true;
    }


    private loadMoreData(): void {
        if (this.isLoading) return;

        this.isLoading = true;
        this.currentPage++;
        const mergedObj = Object.assign({}, { page: this.currentPage, page_size: this.pageSize }, this.otherInfo);
        NetworkManager.getServerInfo(mergedObj, (success, data) => {
            this.isLoading = false;
            if (success && data.data.length > 0) {
                data.data.forEach((item) => {
                    if (this.createItemFunc)
                        this.createItemFunc(this.content, item)
                });
                this.hasMore = data.data.length === this.pageSize;

            } else {
                this.hasMore = false;
            }
        }, this.serVerUrl);
    }

    initGamePage() {
        console.log("初始化游戏页面", this.node.name);
        this.content.removeAllChildren();
        this.scheduleOnce(() => {
            this.resetPageState();
            GlobalRoot.instance.UiManager.showBlockLayer()
            const mergedObj = Object.assign({}, { page: this.currentPage, page_size: this.pageSize }, this.otherInfo);
            NetworkManager.getServerInfo(mergedObj, (success, data) => {
                if (success && data.data.length > 0) {
                    data.data.forEach((item) => {
                        if (this.createItemFunc)
                            this.createItemFunc(this.content, item)
                    });
                    this.hasMore = data.data.length === this.pageSize;
                }
            }, this.serVerUrl);

        })



    }


    public scrollEvent() {
        // 集成自动裁剪透明度，降低 drawcall
        if (this.content) {
            CommonUtils.clipChildrenOpacity(this.content, 100);
        }
    }




    // update (dt) {}
}
